package io.renren.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.utils.Constant;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.sys.dao.MySysRoleDao;
import io.renren.modules.sys.dao.MySysUserDao;
import io.renren.modules.sys.entity.MySysRoleEntity;
import io.renren.modules.sys.service.MySysRoleMenuService;
import io.renren.modules.sys.service.MySysRoleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Service("MySysRoleService")
public class MySysRoleServiceImpl extends ServiceImpl<MySysRoleDao, MySysRoleEntity> implements MySysRoleService {
    @Autowired
    private MySysUserDao mySysUserDao;

    @Autowired
    private MySysRoleMenuService mySysRoleMenuService;

    @Override
    public List<Long> queryRoleIdList(Long createUserId) {
        return baseMapper.queryIdList(createUserId);
    }

    @Override
    public void update(MySysRoleEntity role) {

        baseMapper.updateById(role);

        //检查权限是否越权
        checkPerms(role);

        //保存角色与菜单关系
        mySysRoleMenuService.saveOrUpdate(role.getRoleId(),role.getMenuIdList());
    }

    @Override
    public PageUtils queryPage(HashMap<String, Object> params) {
        String roleName = (String) params.get("roleName");
        Long createUserId = (Long) params.get("createUserId");

        IPage<MySysRoleEntity> page = this.page(
                new Query<MySysRoleEntity>().getPage(params),
                new QueryWrapper<MySysRoleEntity>()
                        .like(StringUtils.isNotBlank(roleName), "roleName", roleName)
                        .eq(createUserId != null, "create_user_id", createUserId)
        );
        return new PageUtils(page);
    }

    private void checkPerms(MySysRoleEntity role) {
        if (role.getCreateUserId() == Constant.SUPER_ADMIN) {
            return;
        }

        List<Long> menuIdList = mySysUserDao.queryAllMenuId(role.getCreateUserId());

        if (!menuIdList.containsAll(role.getMenuIdList())) {
            throw new RRException("新增角色的权限，已超出你的权限范围");
        }
    }
}
